//
//  PublicObj.m
//  WuyouTang
//
//  Created by YunBao on 2018/6/6.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "PublicObj.h"
#import <CommonCrypto/CommonCrypto.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <WXApi.h>
#import "RKUUIDManager.h"
#import "sys/utsname.h"
#import "UIImage+RKImgSize.h"
#import <ShareSDK/ShareSDK.h>
#import <JPUSHService.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import "YBInvitationView.h"
#import "YBYoungSmall.h"

@interface PublicObj()
@property (nonatomic, strong) MPVolumeView *volumeView;
@end

@implementation PublicObj

static PublicObj *_publicInstance = nil;

+(instancetype)publicInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _publicInstance = [[super allocWithZone:NULL]init];
    });
    return _publicInstance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    return  [self publicInstance];
}

-(MPVolumeView *)volumeView {
    if (!_volumeView) {
        _volumeView = [[MPVolumeView alloc] init];
        _volumeView.frame = CGRectMake(-1000, -1000, 100, 100);
    }
    return _volumeView;
}
/// 添加系统音量view
- (void)addSystemVolumeView {
    [self.volumeView removeFromSuperview];
}

/// 移除系统音量view
- (void)removeSystemVolumeView {
    [[UIApplication sharedApplication].keyWindow addSubview:self.volumeView];
}
- (void)addCusDelayedRemove;{
    [self removeSystemVolumeView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addSystemVolumeView];
    });
    
}

#pragma mark - 单行文本长度计算
+(CGSize)sizeWithString:(NSString *)string andFont:(UIFont *)font {
    CGSize size = [string sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    return size;
}
#pragma mark - 多行计算frame
+(CGRect)rectWithString:(NSString *)string andFont:(UIFont *)font maxWidth:(CGFloat)width {
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil] context:nil];
    return rect;
}
#pragma mark - 登录逾期
+(void)tokenExpired:(NSString *)msg {
    if (![PublicObj checkNull:msg]) {
        [MBProgressHUD showPop:msg];
    }
    if ([[YBBaseAppDelegate sharedAppDelegate].topViewController isKindOfClass:[DspLoginVC class]]) {
        return;
    }
    [self resetUserToVisitor];
    DspLoginVC *login = [[DspLoginVC alloc]init];
    login.showAlert = YES;
    login.isOverdue = YES;
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:login animated:NO];
    
    /*
    //延迟1.3在跳回,因为YBMsgPop提示动画是1.2,直接跳动画就销毁了
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIApplication *app =[UIApplication sharedApplication];
        AppDelegate *app2 = (AppDelegate*)app.delegate;
        DspLoginVC *login = [[DspLoginVC alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        app2.window.rootViewController = nav;
    });*/
    
}

#pragma mark - 返回游客信息
+(NSDictionary *)visitorDic{
    NSDictionary *dic = @{
                          @"age":@"18",
                          @"coin":@"0",
                          @"area":@"",
                          @"avatar" : @"http://livedemo.yunbaozhibo.com/default.jpg",
                          @"avatar_thumb" : @"http://livedemo.yunbaozhibo.com/default_thumb.jpg",
                          @"birthday" : @"",
                          @"city" : @"",
                          @"code" : @"",
                          @"hometown":@"",
                          @"id" : @"-9999",
                          @"isreg" : @"0",
                          @"province" : @"",
                          @"sex" : @"2",
                          @"signature" : @"",
                          @"token" : @"-9999",
                          @"user_nickname" : @"游客",
                          };
    return dic;
}

#pragma mark - 提醒游客请登录
+(void)warnLogin {
    //有弹窗--提示是否登录
    /*
    UIViewController *currentVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIAlertController *alertContro = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertContro addAction:cancleAction];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DspLoginVC *login =[[DspLoginVC alloc]init];
        login.youke = @"youke";
        UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:login];
        [currentVC presentViewController:navi animated:YES completion:nil];
    }];
    [alertContro addAction:sureAction];
    [currentVC presentViewController:alertContro animated:YES completion:nil];
    */
    //无弹窗--直接进入登录
    /*
    UIViewController *currentVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    DspLoginVC *login =[[DspLoginVC alloc]init];
    login.youke = @"youke";
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:login];
    [currentVC presentViewController:navi animated:YES completion:nil];
     */
    
    DspLoginVC *login = [[DspLoginVC alloc]init];
    login.showAlert = YES;
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:login animated:NO];
}

#pragma mark - 根据色值获取图片
+(UIImage*)getImgWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f,0.0f, 1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
+(UIImage*)getImgWithColor:(UIColor *)color withSize:(CGSize)size{
    
    CGRect rect = CGRectMake(0.0f,0.0f, size.width,size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark - 设置上图下文字
+(UIButton*)setUpImgDownText:(UIButton *)btn {
    /*
     多处使用，不要随意更改，
     */
    [btn.titleLabel sizeToFit];
    CGFloat textW = [self sizeWithString:btn.titleLabel.text andFont:btn.titleLabel.font].width;
    CGFloat totalH = btn.imageView.frame.size.height + btn.titleLabel.frame.size.height;
    CGFloat totalW = btn.imageView.frame.size.width + textW;
    CGFloat allowanceW = totalW - btn.frame.size.width;
    CGFloat spaceH = 5;
    
    CGFloat btnW = btn.size.width;
    CGFloat btnImgW = btn.imageView.size.width;
    
    if (allowanceW>0) {
        //标题+图片宽度大于按钮宽度
        [btn setImageEdgeInsets:UIEdgeInsetsMake(-(totalH - btn.imageView.frame.size.height),(btnW-btnImgW)/2, 0.0, -(btnW-btnImgW)/2)];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(spaceH, -btn.imageView.frame.size.width, -(totalH - btn.titleLabel.frame.size.height),0)];
    }else {
        //标题+图片宽度小于按钮宽度
        [btn setImageEdgeInsets:UIEdgeInsetsMake(-(totalH - btn.imageView.frame.size.height),0.0, 0.0, -btn.titleLabel.frame.size.width)];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(spaceH, -btn.imageView.frame.size.width, -(totalH - btn.titleLabel.frame.size.height),0.0)];
    }
    /*
    CGFloat allowanceW = (totalW - btn.frame.size.width) > 0 ? (totalW - btn.frame.size.width)/2:0;
    //设置按钮图片偏移
    [btn setImageEdgeInsets:UIEdgeInsetsMake(-(totalH - btn.imageView.frame.size.height),0.0, 0.0, -btn.titleLabel.frame.size.width-allowanceW)];
    //设置按钮标题偏移
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(spaceH, -btn.imageView.frame.size.width-allowanceW, -(totalH - btn.titleLabel.frame.size.height),0.0)];
     */
    
    return btn;
}
//自定义间距上图下文字
+(UIButton*)setUpImgDownText:(UIButton *)btn space:(CGFloat)space {
    
    CGFloat textW = [self sizeWithString:btn.titleLabel.text andFont:btn.titleLabel.font].width;
    CGFloat totalH = btn.imageView.frame.size.height + btn.titleLabel.frame.size.height;
    CGFloat totalW = btn.imageView.frame.size.width + textW;
    CGFloat allowanceW = (totalW - btn.frame.size.width) > 0 ? (totalW - btn.frame.size.width)/2.0 : 0;
    CGFloat spaceH = space;
    //设置按钮图片偏移
    [btn setImageEdgeInsets:UIEdgeInsetsMake(-(totalH - btn.imageView.frame.size.height),0.0, 0.0, -btn.titleLabel.frame.size.width-allowanceW)];
    //设置按钮标题偏移
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(spaceH, -btn.imageView.frame.size.width-allowanceW, -(totalH - btn.titleLabel.frame.size.height),0.0)];
    
    return btn;
}

#pragma mark - 重设root
+(void)resetVC:(UIViewController*)vc{
    UIApplication *app =[UIApplication sharedApplication];
    AppDelegate *app2 = (AppDelegate*)app.delegate;
    YBNavigationController *nav = [[YBNavigationController alloc]initWithRootViewController:vc];
    NSLog(@"1031=ob1===%lu====:%@",app2.window.subviews.count,app2.window.subviews);
    [app2.window removeAllSubViews];
    NSLog(@"1031=ob2===%lu====:%@",app2.window.subviews.count,app2.window.subviews);
    app2.window.rootViewController = nav;
}

#pragma mark - 根据图片名拼接文件路径
+(NSString *)getFilePathWithImageName:(NSString *)imageName {
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    return nil;
}
#pragma mark - 以当前时间合成视频名称
+(NSString *)getNameBaseCurrentTime:(NSString *)suf {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *nameStr = [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:suf];
    return [NSString stringWithFormat:@"%@_IOS_%@",[Config getOwnID],nameStr];
}

#pragma mark - 判断是不是本地视频
+ (BOOL)judgeAssetisInLocalAblum:(PHAsset *)asset {
    __block BOOL result = NO;
    if (@available(iOS 10.0, *)) {
        // https://stackoverflow.com/questions/31966571/check-given-phasset-is-icloud-asset
        // 这个api虽然是9.0出的，但是9.0会全部返回NO，未知原因，暂时先改为10.0
        NSArray *resourceArray = [PHAssetResource assetResourcesForAsset:asset];
        if (resourceArray.count) {
            result = [[resourceArray.firstObject valueForKey:@"locallyAvailable"] boolValue];
        }
    } else {
        PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
        option.networkAccessAllowed = NO;
        option.synchronous = YES;
        
        [[PHCachingImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            result = imageData ? YES : NO;
        }];
    }
    return result;
}
#pragma mark - 权限相关
+ (BOOL)havePhotoLibraryAuthority
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) {
        return YES;
    }
    return NO;
}

#pragma mark - 原图-小-恢复
+(CAAnimation*)bigToSmallRecovery {
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 1;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.3, 0.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.3, 0.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    animation.values = values;
    return animation;
}

#pragma mark - 原图-大-小
+(CAAnimation*)smallToBigToSmall {
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 1.0;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.3, 0.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    
    animation.values = values;
    return animation;
}

#pragma mark - 原图-小-保持
+(CAAnimation*)originToSmall {
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.2;
    NSMutableArray *values = [NSMutableArray array];
   
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    
    animation.values = values;
    return animation;
}
#pragma mark - 原图-大-小-恢复
+(CAAnimation*)originToBigToSmallRecovery {
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.3, 0.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    animation.values = values;
    return animation;
}

#pragma mark - 观看页面上下切换，并且未关注的情况下的过渡动画
+(CAAnimation*)followShowTransition {
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.6, 0.6, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.4, 0.4, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.3, 0.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.4, 0.4, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.6, 0.6, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    animation.values = values;
    return animation;
}



#pragma mark - 按钮按下执行动画(录音)
+(CAAnimation*)touchDownAnimation {
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 1;
    animation.repeatCount = MAXFLOAT;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.4, 1.4, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.6, 1.6, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.7, 1.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.6, 1.6, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.4, 1.4, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    animation.values = values;
    return animation;
}
#pragma mark - 旋转动画
+(CABasicAnimation*)rotationAnimation {
    CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotate.toValue = @(2 * M_PI);
    rotate.duration = 5;
    rotate.repeatCount = MAXFLOAT;
    return rotate;
}

#pragma mark - 动画组
+(CAAnimationGroup*)caGroup{
    //路径
    CAAnimationGroup *group = [[CAAnimationGroup alloc]init];
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.calculationMode = kCAAnimationPaced;
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = YES;
    CGMutablePathRef curvedPath = CGPathCreateMutable();
    //起点
    CGPathMoveToPoint(curvedPath, NULL, 50, 55);
    //辅助点和终点--- 父视图 85*50（唱片 50*50 ）
    CGPathAddQuadCurveToPoint(curvedPath, NULL, 6, 45, 16, -5);
    pathAnimation.path = curvedPath;
    CGPathRelease(curvedPath);
    
    //缩放
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.4, 1.4, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.6, 1.6, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.7, 1.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.8, 1.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.9, 1.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.1, 2.1, 1.0)]];
    
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 0, 1)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.8, 0, 0, 1)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.7, 0, 0, 1)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.6, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.5, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 1, 0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.9, 0, 1, 0)]];
    
    animation.values = values;
    
    //透明
    CAKeyframeAnimation *opacityAnimaton = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
    opacityAnimaton.values = @[@1,@1,@1,@1,@1,@0.9,@0.8,@0.7,@0.6,@0.5,@0.4,@0.3];
    
    group.animations = @[pathAnimation,animation,opacityAnimaton];
    group.duration = 3.0;
    group.repeatCount = MAXFLOAT;
    group.fillMode = kCAFillModeForwards;
    return group;
}
#pragma mark - MD5
+(NSString *)stringToMD5:(NSString *)str {
    //1.首先将字符串转换成UTF-8编码, 因为MD5加密是基于C语言的,所以要先把字符串转化成C语言的字符串
    const char *fooData = [str UTF8String];
    //2.然后创建一个字符串数组,接收MD5的值
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    //3.计算MD5的值, 这是官方封装好的加密方法:把我们输入的字符串转换成16进制的32位数,然后存储到result中
    CC_MD5(fooData, (CC_LONG)strlen(fooData), result);
    /**
     第一个参数:要加密的字符串
     第二个参数: 获取要加密字符串的长度
     第三个参数: 接收结果的数组
     */
    //4.创建一个字符串保存加密结果
    NSMutableString *saveResult = [NSMutableString string];
    //5.从result 数组中获取加密结果并放到 saveResult中
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [saveResult appendFormat:@"%02x", result[i]];
    }
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     NSLog("%02X", 0x888);  //888
     NSLog("%02X", 0x4); //04
     */
    return saveResult;
}
#pragma mark - 检查为空
+(BOOL)checkNull:(NSString *)str {
    if ([str isEqual:@"<null>"]||[str isEqual:@"(null)"]||[str isKindOfClass:[NSNull class]]||str.length==0) {
        return YES;
    }
    return NO;
}
#pragma mark - 双击点赞
+(void)doubleClickShowZan:(UIView *)sueprView withCenter:(CGPoint)center{
    
    __block UIImageView *imgIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_zan_sel"]];
    imgIV.frame = CGRectMake(0, 0, 50, 50);
    imgIV.center = center;
    [sueprView addSubview:imgIV];
    
    CGFloat allDuration = 1.0;
    
    NSArray *angleArray = @[@(60),@(75),@(90),@(105),@(120)];
    
    int randowm = arc4random() % (angleArray.count);
    
    CGFloat angle = [angleArray[randowm] floatValue];
    NSLog(@"==%f\n====%@====%d",angle,angleArray[randowm],randowm);
    //旋转
    CAKeyframeAnimation* rotation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    NSMutableArray *ro_va = [NSMutableArray array];
    [ro_va addObject:[NSValue valueWithCATransform3D:CATransform3DMakeRotation(angle, 0, 0, 1)]];
    
    rotation.values = ro_va;
    
    
    //缩放
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(3.5, 3.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.4, 1.4, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.6, 1.6, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.7, 1.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.8, 1.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.9, 1.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.1, 2.1, 1.0)]];
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.2, 2.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.3, 2.3, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.4, 2.4, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.5, 2.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.6, 2.6, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.7, 2.7, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.8, 2.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(2.9, 2.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(3.0, 3.0, 1.0)]];
    animation.values = values;
    
    //透明
    CAKeyframeAnimation *opacityAnimaton = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
    opacityAnimaton.values = @[@1.0,@1.0,@1.0,@1.0,@1.0,@0.9,@0.8,@0.7,@0.6,@0.5,@0.4,@0.3];
    
    //组
    CAAnimationGroup *group = [[CAAnimationGroup alloc]init];
    group.animations = @[animation,opacityAnimaton,rotation];
    group.duration = allDuration;
    group.repeatCount = 1;
    group.fillMode = kCAFillModeForwards;
    group.removedOnCompletion = NO;
    
    [imgIV.layer addAnimation:group forKey:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(allDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [imgIV removeFromSuperview];
        imgIV = nil;
    });
}
#pragma mark - 创建emoji正则表达式
+(NSArray <NSTextCheckingResult *> *)machesWithPattern:(NSString *)pattern  andStr:(NSString *)str {
    NSError *error = nil;
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (error) {
        NSLog(@"正则表达式创建失败");
        return nil;
    }
    return [expression matchesInString:str options:0 range:NSMakeRange(0, str.length)];
}
#pragma mark -  画一条线
+(UIView *)lineViewWithFrame:(CGRect)frame andColor:(UIColor *)color andView:(UIView *)view{
    UIView *lineView = [[UIView alloc]initWithFrame:frame];
    lineView.backgroundColor = color;
    [view addSubview:lineView];
    return lineView;
}

#pragma mark - 获取系统音量滑块
+(UISlider*)setSystemVolumSliderWithSuperViwe:(UIViewController *)superView{

    static UISlider * volumeViewSlider = nil;
    MPVolumeView *volumeView;
    if (volumeViewSlider == nil) {
        volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(-1000, -1000, 40, 40)];
        
        [superView.view addSubview:volumeView];
        for (UIView* newView in volumeView.subviews) {
            if ([newView.class.description isEqualToString:@"MPVolumeSlider"]){
                volumeViewSlider = (UISlider*)newView;
                break;
            }
        }
    }
    [volumeView setHidden:NO];
    [volumeView setShowsRouteButton:YES];
    [volumeView setShowsVolumeSlider:YES];
    return volumeViewSlider;
}
+(CGFloat)getSysOutputVolume {
    CGFloat volume = [AVAudioSession sharedInstance].outputVolume;
    return volume;
}
#pragma mark - 获取缩略图(需要导入AVFoundation.h)
+(UIImage*)getVideoPreViewImageWithPath:(NSURL *)videoPath {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoPath options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time   = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error  = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img   = [[UIImage alloc] initWithCGImage:image];
    return img;
}

#pragma mark - /** 获取启动图 */
+ (UIImage *)getLaunchImage{
    UIImage *launchImg = [[UIImage alloc] init];
    NSString *orientation = @"";
    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UIInterfaceOrientation statusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (statusBarOrientation == UIInterfaceOrientationLandscapeLeft || statusBarOrientation == UIInterfaceOrientationLandscapeRight) {
        orientation = @"Landscape";
    } else {
        orientation = @"Portrait";
    }
    NSArray *imgsInfoArr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UILaunchImages"];
    for (NSDictionary *info in imgsInfoArr) {
        CGSize imgSize = CGSizeFromString(info[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imgSize, screenSize) && [orientation isEqualToString:info[@"UILaunchImageOrientation"]] ) {
            launchImg = [UIImage imageNamed:info[@"UILaunchImageName"]];
            if (launchImg.scale == scale) {
                break;
            }
        }
    }
    return launchImg;

}
#pragma mark - /** 获取版本号 */
+(NSString *)getAppBuild {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSNumber *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSString *build = [NSString stringWithFormat:@"%@",app_build];
    return build;
}

+(BOOL)isUp{
    if ([[PublicObj getAppBuild] isEqual:[common ios_shelves]]) {
        return YES;
    }
    return NO;
}

+(NSString *)getAppName;{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    return app_name;
}
+(CGFloat)getSysVersion{
    return [[[UIDevice currentDevice] systemVersion] floatValue];
}
#pragma mark - 获取App头像
+(UIImage *)getAppIcon {
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
    UIImage *img= [UIImage imageNamed:icon];
    return img;
}
#pragma mark - /** 字典字符串加(解)密排序 */
+ (NSString *)sortString:(NSDictionary *)dic{
    
    //  2. 非数字型字符串（注意用compare比较要剔除空数据（nil））
    NSString *returnStr = @"";
    NSArray *charArray = [dic allKeys];
    
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    
    NSArray *resultArray2 = [charArray sortedArrayUsingComparator:sort];
    for (int i = 0; i < resultArray2.count; i++) {
        NSString *str = resultArray2[i];
        if (i != resultArray2.count - 1) {
            returnStr = [NSString stringWithFormat:@"%@%@=%@&",returnStr,str,minstr([dic valueForKey:str])];
        }else{
            returnStr = [NSString stringWithFormat:@"%@%@=%@&562d4226cb2a2b4f74b3ef4340828b5d",returnStr,str,minstr([dic valueForKey:str])];
        }
    }
    return [self stringToMD5:returnStr];
}
+ (NSString *)decrypt:(NSString *)code{
    if ([PublicObj checkNull:code]) {
        return @"";
    }
    NSString* str = @"HmTPvkJ3otK5gp.COdrAi:q09Z62ash-QGn8V;FNIlbfM/D74Wj&S_E=UzYuw?1ecxXyLRB";
    NSInteger strl = str.length;
    
    NSInteger len = code.length;
    
    NSString* newCode = @"";
    for(int i = 0;i < len; i++){
        NSString *codeIteam = [code substringWithRange:NSMakeRange(i, 1)];

        for(int j = 0; j < strl; j++){
            NSString *strIteam = [str substringWithRange:NSMakeRange(j, 1)];
            if([strIteam isEqual:codeIteam]){
                if(j == 0){
                    newCode = [NSString stringWithFormat:@"%@%@",newCode,[str substringWithRange:NSMakeRange(strl - 1, 1)]];
                }else{
                    newCode = [NSString stringWithFormat:@"%@%@",newCode,[str substringWithRange:NSMakeRange(j-1, 1)]];
                }
            }
        }
    }
    return newCode;
}

#pragma mark - 小程序
+ (void)openWXMiniProgram:(NSString *)path{
    YBWeakSelf;
    [ShareSDK getUserInfo:SSDKPlatformTypeWechat onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        if (state == SSDKResponseStateSuccess) {
            NSLog(@"uid=%@",user.uid);
            NSLog(@"%@",user.credential);
            NSLog(@"token=%@",user.credential.token);
            NSLog(@"nickname=%@",user.nickname);
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf gogoWeChat:path];
            });
        } else if (state == 2 || state == 3) {
            [MBProgressHUD showError:YZMsg(@"未获取授权")];
        }
    }];
    
}
+ (void)gogoWeChat:(NSString *)path{
    /*! @brief WXApi的成员函数，向微信终端程序注册第三方应用。
     *
     * 需要在每次启动第三方应用程序时调用。
     * @attention 请保证在主线程中调用此函数
     * @param appid 微信开发者ID
     * @param universalLink 微信开发者Universal Link
     * @return 成功返回YES，失败返回NO。
     */
    [WXApi registerApp:WechatAppId universalLink:WechatUniversalLink];
    
    /*! @brief WXLaunchMiniProgramReq对象, 可实现通过sdk拉起微信小程序
     *
     * @note 返回的WXLaunchMiniProgramReq对象是自动释放的
     */
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    //拉起的小程序的username（小程序的原始ID）
    launchMiniProgramReq.userName = WechatUsername;
    //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
    launchMiniProgramReq.path = path;
    //拉起小程序的类型
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease;
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        NSLog(@"拉起小程序结果=%d",success);
    }];
}
#pragma mark - /** git 转 data */
+(NSData *)gifConvertDataWithName:(NSString *)gifName{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:gifName ofType: @"gif"];
    NSData *gifData = [NSData dataWithContentsOfFile: filePath];
    return gifData;
}
#pragma mark - /** 封面width、height */
+(void)getThumbSizeWithUrl:(NSString *)url complete:(ThumbSizeBlock)complete {
    
    if (complete) {
        complete(0,1);
    }
    return;
    /*
    if (![[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"%@width",url]]) {
        CGSize imageSize = [UIImage rk_getImageSizeWithURL:url];
        if (complete) {
            complete(imageSize.width,imageSize.height);
        }
        [[NSUserDefaults standardUserDefaults] setObject:@(imageSize.width) forKey:[NSString stringWithFormat:@"%@width",url]];
        [[NSUserDefaults standardUserDefaults] setObject:@(imageSize.height) forKey:[NSString stringWithFormat:@"%@height",url]];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }else {
        CGFloat img_width = [[[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"%@width",url]] floatValue];
        CGFloat img_height = [[[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"%@height",url]] floatValue];;
        if (complete) {
            complete(img_width,img_height);
        }
    }
     */
}

#pragma mark - /** 获取UUID */
+(NSString *)getDeviceUUID {
    return [RKUUIDManager getUUID];
}

#pragma mark - 设置视图左上圆角
/**
 设置视图左上圆角
 
 @param leftC 左上半径
 @param rightC 又上半径
 @param view 父视图
 @return layer
 */
+(CAShapeLayer *)setViewLeftTop:(CGFloat)leftC andRightTop:(CGFloat)rightC andView:(UIView *)view{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(leftC, rightC)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    return maskLayer;
}

#pragma mark - 图片压缩相关 开始
+(UIImage*)scaleImage:(UIImage *)image scaleToSize:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
+(CGSize)getObjSize:(CGSize)sourceSize; {
    CGSize objSize = CGSizeMake(sourceSize.width, sourceSize.height);
    if (objSize.height >= objSize.width) {
        if([self supportCompressSize:CGSizeMake(720, 1280) objSize:objSize]){
            objSize = [self compress:CGSizeMake(720, 1280) objSize:objSize];
        }
    }else{
        if([self supportCompressSize:CGSizeMake(1280, 720) objSize:objSize]){
            objSize = [self compress:CGSizeMake(1280, 720) objSize:objSize];
        }
    }
    return objSize;
}

//判断是否需要压缩图片
+(BOOL)supportCompressSize:(CGSize)compressSize objSize:(CGSize)objSize {
    if (objSize.width >= compressSize.width && objSize.height >= compressSize.height) {
        return YES;
    }
    if (objSize.width >= compressSize.height && objSize.height >= compressSize.width) {
        return YES;
    }
    return NO;
}

//获得压缩后图片大小
+(CGSize)compress:(CGSize)compressSize objSize:(CGSize)objSize {
    CGSize size = CGSizeZero;
    if (compressSize.height / compressSize.width >= objSize.height / objSize.width) {
        size.width = compressSize.width;
        size.height = compressSize.width * objSize.height / objSize.width;
    }else{
        size.height = compressSize.height;
        size.width = compressSize.height * objSize.width / objSize.height;
    }
    return size;
}
#pragma mark - 图片压缩相关 结束

#pragma mark - 渐变色
+(void)addGradientWithFromColor:(UIColor *)formColor andEndColor:(UIColor *)endColor andView:(UIView *)view direction:(int)dire{
    CAGradientLayer *gradient = [CAGradientLayer layer];
    //设置开始和结束位置(设置渐变的方向)
    //dire:0-横向 1-纵向 2-斜向
    if (dire == 1) {
        gradient.startPoint = CGPointMake(0, 0);
        gradient.endPoint = CGPointMake(0, 1);
    }else if (dire == 2){
        gradient.startPoint = CGPointMake(0, 0);
        gradient.endPoint = CGPointMake(0, 1);
    }else {
        gradient.startPoint = CGPointMake(0, 0);
        gradient.endPoint = CGPointMake(1, 0);
    }
    gradient.frame =CGRectMake(0,0,view.width,view.height);
    gradient.colors = [NSArray arrayWithObjects:(id)formColor.CGColor,(id)endColor.CGColor,nil];
    [view.layer insertSublayer:gradient atIndex:0];
}
#pragma mark - 比较两个时间的大小(date01 老的时间、date02 新的时间 返回 1 -1 0)
+(int)compareDate:(NSString*)date01 withDate:(NSString*)date02 {
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *dt1 = [[NSDate alloc]init];
    NSDate *dt2 = [[NSDate alloc]init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result){
        //date02比date01大
        case NSOrderedAscending:
            ci = 1;
            break;
        //date02比date01小
        case NSOrderedDescending:
            ci = -1;
            break;
        //date02=date01
        case NSOrderedSame:
            ci = 0;
            break;
        default:
            NSLog(@"erorr dates %@, %@", dt2, dt1);
            break;
     }
    return ci;

}
#pragma mark - 网络类型、手机类型
/*
+ (NSString *)getNetworkType {
    NSString *network = @"";
    if ([[UIDevice currentDevice].systemVersion floatValue]>=13) {
        return network;
    }else
    if (iPhoneX) {
        UIApplication *app = [UIApplication sharedApplication];
        id statusBar = [app valueForKeyPath:@"statusBar"];

        //        iPhone X
        id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
        UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
        NSArray *subviews = [[foregroundView subviews][2] subviews];
        for (id subview in subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
                network = @"WIFI";
            }else if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarStringView")]) {
                network = [subview valueForKeyPath:@"originalText"];
            }
        }
    }else {
        UIApplication *app = [UIApplication sharedApplication];
        id statusBar = [app valueForKeyPath:@"statusBar"];
        //非 iPhone X
        UIView *foregroundView = [statusBar valueForKeyPath:@"foregroundView"];
        NSArray *subviews = [foregroundView subviews];
        for (id subview in subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
                int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
                switch (networkType) {
                    case 0:
                        network = @"NONE";
                        break;
                    case 1:
                        network = @"2G";
                        break;
                    case 2:
                        network = @"3G";
                        break;
                    case 3:
                        network = @"4G";
                        break;
                    case 5:
                        network = @"WIFI";
                        break;
                    default:
                        break;
                }
            }
        }
    }
    if ([network isEqualToString:@""]) {
        network = @"NO DISPLAY";
    }
    return network;
}
*/
/*
+ (NSString *)getNetworkType {
    UIApplication *app = [UIApplication sharedApplication];
    id statusBar = nil;
    NSString *network = @"";
    if (@available(iOS 13.0, *)) {
        UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
        if ([statusBarManager respondsToSelector:@selector(createLocalStatusBar)]) {
            UIView *localStatusBar = [statusBarManager performSelector:@selector(createLocalStatusBar)];
            if ([localStatusBar respondsToSelector:@selector(statusBar)]) {
                statusBar = [localStatusBar performSelector:@selector(statusBar)];
            }
        }
#pragma clang diagnostic pop
        if (statusBar) {
//            UIStatusBarDataCellularEntry
            id currentData = [[statusBar valueForKeyPath:@"_statusBar"] valueForKeyPath:@"currentData"];
            id _wifiEntry = [currentData valueForKeyPath:@"wifiEntry"];
            id _cellularEntry = [currentData valueForKeyPath:@"cellularEntry"];
            if (_wifiEntry && [[_wifiEntry valueForKeyPath:@"isEnabled"] boolValue]) {
//                If wifiEntry is enabled, is WiFi.
                network = @"WIFI";
            } else if (_cellularEntry && [[_cellularEntry valueForKeyPath:@"isEnabled"] boolValue]) {
                NSNumber *type = [_cellularEntry valueForKeyPath:@"type"];
                if (type) {
                    switch (type.integerValue) {
                        case 0:
//                            无sim卡
                            network = @"NONE";
                            break;
                        case 1:
                            network = @"1G";
                            break;
                        case 4:
                            network = @"3G";
                            break;
                        case 5:
                            network = @"4G";
                            break;
                        default:
//                            默认WWAN类型
                            network = @"WWAN";
                            break;
                            }
                        }
                    }
                }
    }else {
        statusBar = [app valueForKeyPath:@"statusBar"];
        if (IS_IPHONE_X== 1) {
//            刘海屏
                id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
                UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
                NSArray *subviews = [[foregroundView subviews][2] subviews];
                
                if (subviews.count == 0) {
//                    iOS 12
                    id currentData = [statusBarView valueForKeyPath:@"currentData"];
                    id wifiEntry = [currentData valueForKey:@"wifiEntry"];
                    if ([[wifiEntry valueForKey:@"_enabled"] boolValue]) {
                        network = @"WIFI";
                    }else {
//                    卡1:
                        id cellularEntry = [currentData valueForKey:@"cellularEntry"];
//                    卡2:
                        id secondaryCellularEntry = [currentData valueForKey:@"secondaryCellularEntry"];

                        if (([[cellularEntry valueForKey:@"_enabled"] boolValue]|[[secondaryCellularEntry valueForKey:@"_enabled"] boolValue]) == NO) {
//                            无卡情况
                            network = @"NONE";
                        }else {
//                            判断卡1还是卡2
                            BOOL isCardOne = [[cellularEntry valueForKey:@"_enabled"] boolValue];
                            int networkType = isCardOne ? [[cellularEntry valueForKey:@"type"] intValue] : [[secondaryCellularEntry valueForKey:@"type"] intValue];
                            switch (networkType) {
                                    case 0://无服务
                                    network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"NONE"];
                                    break;
                                    case 3:
                                    network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"2G/E"];
                                    break;
                                    case 4:
                                    network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"3G"];
                                    break;
                                    case 5:
                                    network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"4G"];
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                
                }else {
                    
                    for (id subview in subviews) {
                        if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
                            network = @"WIFI";
                        }else if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarStringView")]) {
                            network = [subview valueForKeyPath:@"originalText"];
                        }
                    }
                }
                
            }else {
//                非刘海屏
                UIView *foregroundView = [statusBar valueForKeyPath:@"foregroundView"];
                NSArray *subviews = [foregroundView subviews];
                
                for (id subview in subviews) {
                    if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
                        int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
                        switch (networkType) {
                            case 0:
                                network = @"NONE";
                                break;
                            case 1:
                                network = @"2G";
                                break;
                            case 2:
                                network = @"3G";
                                break;
                            case 3:
                                network = @"4G";
                                break;
                            case 5:
                                network = @"WIFI";
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
    }

    if ([network isEqualToString:@""]) {
        network = @"NO DISPLAY";
    }
    return network;
}
*/

+(void)saveNetReachability:(NSString *)save{
    NSUserDefaults *stanardDef = [NSUserDefaults standardUserDefaults];
    [stanardDef setObject:save forKey:@"yb_new_reachablility"];
    [stanardDef synchronize];
}
+(NSString *)getNetReachability {
    NSUserDefaults *stanardDef = [NSUserDefaults standardUserDefaults];
    NSString *getVal = [stanardDef objectForKey:@"yb_new_reachablility"];
    return getVal;
}
+ (NSString *)getNetworkType {
    if ([self checkNull:[self getNetReachability]] || [[self getNetReachability] isEqual:@"unknown"]) {
        return @"unknown";
    }else if([[self getNetReachability] isEqual:@"wifi"]){
        return @"wifi";
    }else{
        CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
        /// 注意：没有SIM卡，值为空
        NSString *currentStatus;
        NSString *currentNet = @"5G";
        if (@available(iOS 12.1, *)) {
            if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
                NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
                if (radioDic.allKeys.count) {
                    currentStatus = [radioDic objectForKey:radioDic.allKeys[0]];
                }
            }
        }else{
            currentStatus = info.currentRadioAccessTechnology;
        }
        
        if ([currentStatus isEqualToString:CTRadioAccessTechnologyGPRS]) {
            currentNet = @"GPRS";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyEdge]) {
            currentNet = @"2.75G EDGE";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyWCDMA]){
            currentNet = @"3G";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyHSDPA]){
            currentNet = @"3.5G HSDPA";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyHSUPA]){
            currentNet = @"3.5G HSUPA";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMA1x]){
            currentNet = @"2G";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]){
            currentNet = @"3G";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]){
            currentNet = @"3G";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]){
            currentNet = @"3G";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyeHRPD]){
            currentNet = @"HRPD";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyLTE]){
            currentNet = @"4G";
        }else if (@available(iOS 14.1, *)) {
            if ([currentStatus isEqualToString:CTRadioAccessTechnologyNRNSA]){
                currentNet = @"5G NSA";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyNR]){
                currentNet = @"5G";
            }
        }
        return currentNet;
    }
}

/// 此方法谨慎使用【使用到了私有属性,随着系统的升级有可能面临苹果的禁用】
+ (int)getSignalStrength {
    int signalStrength = 0;
    if (@available(iOS 13.0, *)) {
        UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager;
        id statusBar = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
        /*
        if ([statusBarManager respondsToSelector:@selector(createLocalStatusBar)]) {
            UIView *localStatusBar = [statusBarManager performSelector:@selector(createLocalStatusBar)];
            if ([localStatusBar respondsToSelector:@selector(statusBar)]) {
                statusBar = [localStatusBar performSelector:@selector(statusBar)];
            }
        }
        */
        if([statusBarManager respondsToSelector:NSSelectorFromString(@"createLocalStatusBar")]) {
            UIView*localStatusBar = [statusBarManager performSelector:NSSelectorFromString(@"createLocalStatusBar")];
            if([localStatusBar respondsToSelector:NSSelectorFromString(@"statusBar")]){
                statusBar = [localStatusBar performSelector:NSSelectorFromString(@"statusBar")];
            }
        }
#pragma clang diagnostic pop
        if (statusBar) {
            id currentData = [[statusBar valueForKeyPath:@"_statusBar"] valueForKeyPath:@"currentData"];
            id _wifiEntry = [currentData valueForKeyPath:@"wifiEntry"];
            id _cellularEntry = [currentData valueForKeyPath:@"cellularEntry"];
            if (_wifiEntry && [[_wifiEntry valueForKeyPath:@"isEnabled"] boolValue]) {
                // If wifiEntry is enabled, is WiFi.
                if ([_wifiEntry isKindOfClass:NSClassFromString(@"_UIStatusBarDataIntegerEntry")]) {
                // 层级：_UIStatusBarDataNetworkEntry、_UIStatusBarDataIntegerEntry、_UIStatusBarDataEntry
                    signalStrength = [[_wifiEntry valueForKey:@"displayValue"] intValue];
                }
            } else if (_cellularEntry && [[_cellularEntry valueForKeyPath:@"isEnabled"] boolValue]) {
                if ([_cellularEntry isKindOfClass:NSClassFromString(@"_UIStatusBarDataIntegerEntry")]) {
                // 层级：_UIStatusBarDataNetworkEntry、_UIStatusBarDataIntegerEntry、_UIStatusBarDataEntry
                    signalStrength = [[_cellularEntry valueForKey:@"displayValue"] intValue];
                }
            }
        }
    }else {
        if (IS_IPHONE_X == 1) {
            id statusBar = [[UIApplication sharedApplication] valueForKeyPath:@"statusBar"];
            id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
            UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
            int signalStrength = 0;
            
            NSArray *subviews = [[foregroundView subviews][2] subviews];
            
            for (id subview in subviews) {
                if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
                    signalStrength = [[subview valueForKey:@"numberOfActiveBars"] intValue];
                    break;
                }else if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarPersistentAnimationView")]) {//_UIStatusBarStringView
                    signalStrength = [[subview valueForKey:@"numberOfActiveBars"] intValue];
                    break;
                }
            }
            return signalStrength;
        } else {
            
            UIApplication *app = [UIApplication sharedApplication];
            NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
            NSString *dataNetworkItemView = nil;
            int signalStrength = 0;

            for (id subview in subviews) {
                
                if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]] && [[self getNetworkType] isEqualToString:@"WIFI"] && ![[self getNetworkType] isEqualToString:@"NONE"]) {
                    dataNetworkItemView = subview;
                    signalStrength = [[dataNetworkItemView valueForKey:@"_wifiStrengthBars"] intValue];
                    break;
                }
                if ([subview isKindOfClass:[NSClassFromString(@"UIStatusBarSignalStrengthItemView") class]] && ![[self getNetworkType] isEqualToString:@"WIFI"] && ![[self getNetworkType] isEqualToString:@"NONE"]) {
                    dataNetworkItemView = subview;
//                    signalStrength = [[dataNetworkItemView valueForKey:@"_signalStrengthRaw"] intValue];
                    signalStrength = [[dataNetworkItemView valueForKey:@"_signalStrengthBars"] intValue];
                    break;
                }
            }
            return signalStrength;
        }
    }
    return signalStrength;
}
+ (NSString *)iphoneType{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString*phoneType = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if([phoneType  isEqualToString:@"iPhone1,1"])  return @"iPhone-2G";
    if([phoneType  isEqualToString:@"iPhone1,2"])  return @"iPhone-3G";
    if([phoneType  isEqualToString:@"iPhone2,1"])  return @"iPhone-3GS";
    if([phoneType  isEqualToString:@"iPhone3,1"])  return @"iPhone-4";
    if([phoneType  isEqualToString:@"iPhone3,2"])  return @"iPhone-4";
    if([phoneType  isEqualToString:@"iPhone3,3"])  return @"iPhone-4";
    if([phoneType  isEqualToString:@"iPhone4,1"])  return @"iPhone-4S";
    if([phoneType  isEqualToString:@"iPhone5,1"])  return @"iPhone-5";
    if([phoneType  isEqualToString:@"iPhone5,2"])  return @"iPhone-5";
    if([phoneType  isEqualToString:@"iPhone5,3"])  return @"iPhone-5c";
    if([phoneType  isEqualToString:@"iPhone5,4"])  return @"iPhone-5c";
    if([phoneType  isEqualToString:@"iPhone6,1"])  return @"iPhone-5s";
    if([phoneType  isEqualToString:@"iPhone6,2"])  return @"iPhone-5s";
    if([phoneType  isEqualToString:@"iPhone7,1"])  return @"iPhone-6Plus";
    if([phoneType  isEqualToString:@"iPhone7,2"])  return @"iPhone-6";
    if([phoneType  isEqualToString:@"iPhone8,1"])  return @"iPhone-6s";
    if([phoneType  isEqualToString:@"iPhone8,2"])  return @"iPhone-6sPlus";
    if([phoneType  isEqualToString:@"iPhone8,4"])  return @"iPhone-SE";
    if([phoneType  isEqualToString:@"iPhone9,1"])  return @"iPhone-7";
    if([phoneType  isEqualToString:@"iPhone9,2"])  return @"iPhone-7Plus";
    if([phoneType  isEqualToString:@"iPhone10,1"]) return @"iPhone-8";
    if([phoneType  isEqualToString:@"iPhone10,4"]) return @"iPhone-8";
    if([phoneType  isEqualToString:@"iPhone10,2"]) return @"iPhone-8Plus";
    if([phoneType  isEqualToString:@"iPhone10,5"]) return @"iPhone-8Plus";
    if([phoneType  isEqualToString:@"iPhone10,3"]) return @"iPhone-X";
    if([phoneType  isEqualToString:@"iPhone10,6"]) return @"iPhone-X";
    if([phoneType  isEqualToString:@"iPhone11,8"]) return @"iPhone-XR";
    if([phoneType  isEqualToString:@"iPhone11,2"]) return @"iPhone-XS";
    if([phoneType  isEqualToString:@"iPhone11,4"]) return @"iPhone-XSMax";
    if([phoneType  isEqualToString:@"iPhone11,6"]) return @"iPhone-XSMax";
    if([phoneType  isEqualToString:@"iPhone12,1"]) return @"iPhone-11";
    if([phoneType  isEqualToString:@"iPhone12,3"]) return @"iPhone-11Pro";
    if([phoneType  isEqualToString:@"iPhone12,5"]) return @"iPhone-11ProMax";
    if([phoneType  isEqualToString:@"iPhone12,8"]) return @"iPhone-SE2nd";
    if([phoneType  isEqualToString:@"iPhone13,1"]) return @"iPhone-12mini";
    if([phoneType  isEqualToString:@"iPhone13,2"]) return @"iPhone-12";
    if([phoneType  isEqualToString:@"iPhone13,3"]) return @"iPhone-12Pro";
    if([phoneType  isEqualToString:@"iPhone13,4"]) return @"iPhone-12ProMax";
    
    if([phoneType  isEqualToString:@"iPhone14,4"]) return @"iPhone-13mini";
    if([phoneType  isEqualToString:@"iPhone14,5"]) return @"iPhone-13";
    if([phoneType  isEqualToString:@"iPhone14,2"]) return @"iPhone-13Pro";
    if([phoneType  isEqualToString:@"iPhone14,3"]) return @"iPhone-13ProMax";
    if([phoneType  isEqualToString:@"iPhone14,6"]) return @"iPhone-SE3nd";
    
    return phoneType;
}
+ (NSInteger)getDeviceType;{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    NSArray *symbols = [platform componentsSeparatedByString:@","];
    NSInteger number = 0;
    if (symbols.count > 0){
        NSCharacterSet *characterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        number = [[[symbols[0] componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""] integerValue];
    }
    return number;
}
/** 更新pushid */
+(void)updatePushId:(NSString *)pushId;{
    if ([[Config getOwnID] intValue] <= 0) {
        return;
    }
    [WYNetworking postWithUrl:@"Login.upUserPush" Dic:@{@"pushid":pushId} Suc:^(int code, id info, NSString *msg) {
        
    } Fail:^(id fail) {
        
    }];
}

/** 重置为游客 */
+(void)resetUserToVisitor{
   
    [PublicObj updatePushId:@""];
    [Config clearUnified];
    [Config saveUnified:[PublicObj visitorDic]];
    [Config removeCashAccount];
    [[YBImManager shareInstance] imLogout];
    YBTabBarController *root = [self currentTabbar];
    [root setSelectedIndex:0];
    
}
+(YBTabBarController *)currentTabbar{
    NSArray *topA = [YBBaseAppDelegate sharedAppDelegate].topViewController.navigationController.viewControllers;
    NSLog(@"rk_tabbar:%@",topA);
    if (topA.count > 0) {
        UIViewController *vc = topA[0];
        if ([vc isKindOfClass:[YBTabBarController class]]) {
            return (YBTabBarController *)vc;
        }
        return nil;
    }
    return nil;
}
/** 背景模糊图 */
+(UIImageView *)getAvatarEffectWithUrl:(NSString *)avatarUrl{
    UIImageView *avatarEffect = [self getAvatarEffectWithUrl:avatarUrl andFrame:CGRectMake(0, 0, _window_width, _window_height)];
    return avatarEffect;
}
+(UIImageView *)getAvatarEffectWithUrl:(NSString *)avatarUrl andFrame:(CGRect)effectFrame{
    UIImageView *avatarEffect = [[UIImageView alloc]initWithFrame:effectFrame];
    avatarEffect.contentMode = UIViewContentModeScaleAspectFill;
    avatarEffect.clipsToBounds = YES;
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
    effectview.frame = effectFrame;
    [avatarEffect addSubview:effectview];
    
    [avatarEffect sd_setImageWithURL:[NSURL URLWithString:avatarUrl] placeholderImage:[PublicObj getAppIcon]];
    return avatarEffect;
}
#pragma mark - 直播中头像动画
+(CAKeyframeAnimation *)avatarScaleAnimation {
    CAKeyframeAnimation *scaleAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnimation.values = @[@1.0, @0.95, @0.90, @0.85, @0.90, @0.95, @1.0];
    scaleAnimation.repeatCount = MAXFLOAT;
    scaleAnimation.duration = 1.0;
    scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    return scaleAnimation;
}

+(CAKeyframeAnimation *)bottomScaleAnimation {
    CAKeyframeAnimation *scaleAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnimation.values = @[@1.0,@1.05, @1.1, @1.15, @1.10, @1.05,@1.0];
    scaleAnimation.repeatCount = MAXFLOAT;
    scaleAnimation.duration = 1.0;
    scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    return scaleAnimation;
}

#pragma mark - 获取私信未读数量【去除:粉丝、赞、AT、评论、官方】
//+(void)getRoomImUnread:(RoomIMNumBlock)complete {
//        TIMManager *manager = [TIMManager sharedInstance];
//        NSArray *convs = [manager getConversationList];
//        NSMutableArray *arrayd = [NSMutableArray array];
//        int unRead = 0;
//        
//        for (int i = 0; i < convs.count; i ++) {
//            TIMConversation *conv = convs[i];
//            if([conv getType] == TIM_SYSTEM){
//                continue;
//            }else if([conv getType] == TIM_GROUP){
//                continue;
//            }else if ([[conv getReceiver] isEqual:@"dsp_admin_1"] ||
//                      [[conv getReceiver] isEqual:@"dsp_fans"] ||
//                      [[conv getReceiver] isEqual:@"dsp_like"] ||
//                      [[conv getReceiver] isEqual:@"dsp_at"] ||
//                      [[conv getReceiver] isEqual:@"dsp_comment"] ||
//                      [[conv getReceiver] isEqual:@"dsp_user_live"] ||
//                      [[conv getReceiver] isEqual:@"goodsorder_admin"]
//                      ){
//                continue;
//            }
//            /**
//             *dsp_admin_1、dsp_admin_2、dsp_fans、dsp_like、dsp_at、dsp_comment、
//             *dsp_admin_control、dsp_user_live、goodsorder_admin
//             */
//            [arrayd addObject:conv];
//        }
//        for (int i = 0; i < arrayd.count; i ++) {
//            TIMConversation *conv = arrayd[i];
//            int jjj = [conv getUnReadMessageNum];
//            unRead += jjj;
//        }
//    if (complete) {
//        complete(unRead);
//    }
//}
#pragma mark - /** 是否开启了粗体文本 */
+(BOOL)isBlodText;{
    return ![[UIFont preferredFontForTextStyle:UIFontTextStyleBody].fontName hasSuffix:@"-Regular"];
}

#pragma mark - /** 更新同城tab名称 */
+(NSString *)updataNewCity:(NSString *)cityName;{
    NSArray *tabbarArray = [[PublicObj currentTabbar] viewControllers];
//    NSArray *oldTitles = @[@"首页1",@"同城1",@"消息1",@"我1"];
//    for (int i = 0; i<tabbarArray.count; i++) {
//        UINavigationController *navaaaa = tabbarArray[i];
//        navaaaa.tabBarItem.title = oldTitles[i];
//    }
    NSString *showName = YZMsg(@"同城");
    if (cityName.length <= 2) {
        showName = cityName;
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateCity" object:showName];
//    NSArray *newTitles = @[YZMsg(@"首页"),showName,YZMsg(@"消息"),YZMsg(@"我")];
//    for (int i = 0; i<tabbarArray.count; i++) {
//        UINavigationController *navaaaa = tabbarArray[i];
//        navaaaa.tabBarItem.title = newTitles[i];
//    }
//    [PublicObj currentTabbar].tabbar.itemArr =[NSMutableArray arrayWithArray:newTitles] ;
//    [[PublicObj currentTabbar] setViewControllers:tabbarArray];
    return showName;
}
#pragma mark - /** token 验证*/
+(void)tokenAccess:(TokenAccessBlock)complete;{
    int uid = [minstr([Config getOwnID]) intValue];
    if (uid <= 0) {
        complete(NO);
        [PublicObj tokenExpired:@""];
        return;
    }
    [WYNetworking postWithUrl:@"user.iftoken" Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            complete(YES);
        }else {
            complete(NO);
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        complete(NO);
    }];
}
+(void)checkGoodsExistenceWithID:(NSString *)goosID Existence:(GoodsExistenceEvent)existence{
//    NSString *url = [purl stringByAppendingFormat:@"?service=Shop.getGoodExistence"];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"goodsid":goosID,
                            };
    
    [WYNetworking postWithUrl:@"Shop.getGoodExistence" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (existence) {
            existence(code,msg);
        }

        } Fail:^(id fail) {
            
        }];
//    [WYNetworking postWithUrl:url Dic:dic Suc:^(NSDictionary *data, NSString *code, NSString *msg) {
//        if (existence) {
//            existence(code,msg);
//        }
//    } Fail:^(id fail) {
//    }];

}
/**
 计算字符串宽度
 
 @param str 字符串
 @param font 字体
 @param height 高度
 @return 宽度
 */
- (CGFloat)widthOfString:(NSString *)str andFont:(UIFont *)font andHeight:(CGFloat)height{
    return [str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.width;
}

+ (CGFloat)widthOfString:(NSString *)str andFont:(UIFont *)font andHeight:(CGFloat)height{
    return [str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.width;
}
/**
 计算字符串的高度
 
 @param str 字符串
 @param font 字体
 @param width 宽度
 @return 高度
 */
+ (CGFloat)heightOfString:(NSString *)str andFont:(UIFont *)font andWidth:(CGFloat)width{
    return [str boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.height;
}

+(YBButton *)youngAlertBtn {
    YBButton *youngBtn = [YBButton buttonWithType:UIButtonTypeCustom];
    [youngBtn setImage:[UIImage imageNamed:@"青少年-警告"] forState:0];
    [youngBtn setTitle:YZMsg(@"未成年人禁止充值消费") forState:0];
    [youngBtn setTitleColor:Pink_Cor forState:0];
    youngBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -6, 0, 0);
    youngBtn.titleLabel.font = SYS_Font(12);
    return youngBtn;
}

#pragma mark - 各类window弹窗层级布局
+(void)layoutWindowPopLayer;{
    
    YBInvitationView *inviteV = nil;
    YBAlertView *appUpdate = nil;
    YBAlertView *appMaintain = nil;
    YBAlertView *youngAlert = nil;
    YBYoungSmall *youngSmall = nil;
    for (UIView *view in [UIApplication sharedApplication].delegate.window.subviews) {
        if ([view isKindOfClass:[YBInvitationView class]]) {
            inviteV = (YBInvitationView *)view;
        }else if ([view isKindOfClass:[YBAlertView class]]){
            YBAlertView *selfAlert = (YBAlertView *)view;
            if (selfAlert.alertFrom == AlertFrom_YoungModel) {
                youngAlert = selfAlert;
            }else if (selfAlert.alertFrom == AlertFrom_AppUpdate){
                appUpdate = selfAlert;
            }else if (selfAlert.alertFrom == AlertFrom_Maintain){
                appMaintain = selfAlert;
            }
        }else if ([view isKindOfClass:[YBYoungSmall class]]){
            youngSmall = (YBYoungSmall *)view;
        }
    }
    if (inviteV) {
        [[UIApplication sharedApplication].delegate.window bringSubviewToFront:inviteV];
    }
    if (youngAlert) {
        [[UIApplication sharedApplication].delegate.window bringSubviewToFront:youngAlert];
    }
    if (youngSmall) {
        [[UIApplication sharedApplication].delegate.window bringSubviewToFront:youngSmall];
    }
    if (appUpdate) {
        [[UIApplication sharedApplication].delegate.window bringSubviewToFront:appUpdate];
    }
    if (appMaintain) {
        [[UIApplication sharedApplication].delegate.window bringSubviewToFront:appMaintain];
    }
}
#pragma mark - 拒绝协议杀掉app
+(void)appDestroy {
    // Home键退出后台动画效果，此时后台还是挂起状态
    [[UIApplication sharedApplication] performSelector:@selector(suspend)];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
         [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
#pragma clang diagnostic pop
    });
}
#pragma mark - 美颜
+(BOOL)isBaseBeauty;{
    if ([PublicObj checkNull:[common getTISDKKey]] ||
        [PublicObj checkNull:[common getTISDKAppid]]) {
        return YES;
    }
    return NO;
}

+(WYBaseViewController *)currentViewContorller {
//    UIResponder *next = [[YBAppDelegate sharedAppDelegate].topViewController nextResponder];
    UIResponder *next = (UIResponder *)[YBBaseAppDelegate sharedAppDelegate].topViewController;
    do {if ([next isKindOfClass:[WYBaseViewController class]]) {
        return (WYBaseViewController *)next;
    }
        next = [next nextResponder];
    } while (next !=nil);
    return nil;
}
+(NSString *)getDateDisplayString:(NSDate *)date {
    
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc ] init ];
    dateFmt.dateFormat = @"yyyy-MM-dd HH:mm";
    return [dateFmt stringFromDate:date];
}
+(NSString *)getUserDateString:(NSDate *)date{
    NSCalendar *calendar = [ NSCalendar currentCalendar ];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear ;
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc ] init ];
    dateFmt.dateFormat = @"yyyy-MM-dd HH:mm";
    return [dateFmt stringFromDate:date];
}
+ (NSString *)getFriendlyDateString:(NSTimeInterval)timeInterval
                    forConversation:(BOOL)isShort {
    NSDate* theDate = [NSDate dateWithTimeIntervalSince1970:timeInterval/1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSString * FORMAT_PAST_SHORT = @"MM-dd HH:mm";
    [formatter setDateFormat:FORMAT_PAST_SHORT];
    NSString *dateStr = [formatter stringFromDate:theDate];
    return dateStr;

}

#pragma mark - data转字符串
+(NSString *)transformToStringWithData:(id)originData; {
    if (!originData) {
        return @"";
    }
    NSString *getStr = @"not data";
    if ([originData isKindOfClass:[NSData class]]) {
        getStr = [[NSString alloc] initWithData:originData encoding:NSUTF8StringEncoding];
    }
    return getStr;
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
+ (BOOL)isUrlString:(NSString *)string {

  NSString *emailRegex = @"[a-zA-z]+://.*";
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:string];
}

#pragma mark - tabbar消息未读
+(void)setTabbarBadgeValue:(int)value; {
    UIApplication *app =[UIApplication sharedApplication];
    AppDelegate *app2 = (AppDelegate*)app.delegate;
    [app2.rtabbar updateNum:value];
}

+(BOOL)isArray:(id)data; {
    BOOL res = NO;
    if ([data isKindOfClass:[NSArray class]]) {
        res = YES;
    }
    return res;
}
+(BOOL)isDictionary:(id)data; {
    BOOL res = NO;
    if ([data isKindOfClass:[NSDictionary class]]) {
        res = YES;
    }
    return res;
}
+(NSDictionary *)safeDic:(id)originDic; {
    if ([self isDictionary:originDic]) {
        return [NSDictionary dictionaryWithDictionary:originDic];
    }
    return @{};
}
#pragma mark -
+(BOOL)isShopList; {
    NSUserDefaults *userDafault = [NSUserDefaults standardUserDefaults];
    NSString *val = @"0";
    if ([userDafault valueForKey:@"wyt_is_shop_list"]) {
        val = strFormat([userDafault valueForKey:@"wyt_is_shop_list"]);
    }
    return [val boolValue];
}
+(void)changeListState; {
    BOOL oldVal = [self isShopList];
    NSUserDefaults *userDafault = [NSUserDefaults standardUserDefaults];
    if (oldVal) {
        [userDafault setObject:@"0" forKey:@"wyt_is_shop_list"];
    }else {
        [userDafault setObject:@"1" forKey:@"wyt_is_shop_list"];
    }
}
@end
